package com.hcc.flow.server.common.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hcc.flow.server.common.model.ApiResult;

@Component
public class ResponseUtil {

	private static ObjectMapper objectMapper = new ObjectMapper();

	@SuppressWarnings("unchecked")
	public static void responseJson(HttpServletResponse response, int status, Object data) {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Allow-Methods", "*");
			response.setContentType("application/json;charset=UTF-8");
			response.setStatus(status);

			String content = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
			String desdata = content;


			Object newData = null;
			if (data instanceof ApiResult) {
				ApiResult<Object> result = (ApiResult<Object>) data;
				if (!result.getCode().equals("0")) {
					newData = result;
				}
			} else {
				newData = ResultUtil.success(desdata);
			}

			response.getWriter().write(JSONObject.toJSONString(newData));

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
